package com.newgoldcurrency.activities;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.method.LinkMovementMethod;
import android.view.animation.AnimationUtils;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.newgoldcurrency.App;
import com.newgoldcurrency.R;
import com.newgoldcurrency.activities.forgetpassword.ForgetPasswordVerifyActivity;
import com.newgoldcurrency.activities.main.MainActivity;
import com.newgoldcurrency.activities.register.RegisterActivity;
import com.newgoldcurrency.bean.UserBean;
import com.newgoldcurrency.databinding.ActivityLoginBinding;
import com.newgoldcurrency.utils.Tools;
import com.newgoldcurrency.utils.network.Network;
import com.newgoldcurrency.view.LoadingDialog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {
    private final List<Call> calls=new ArrayList<>();
    private ActivityLoginBinding binding;
    private LoadingDialog loading_dialog;
    private ActivityResultLauncher<Intent> launcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        loading_dialog=new LoadingDialog(this);
        binding.loginLogin.setOnClickListener(v -> {
            if (checkDoubleClick()){
                if (loading_dialog != null && !loading_dialog.isShowing()) {
                    loading_dialog.show();
                    if (!binding.loginCb.isChecked()){
                        binding.loginCb.startAnimation(AnimationUtils.loadAnimation(this, R.anim.shake_button));
                        Tools.toast(getString(R.string.check_text));
                        loading_dialog.dismiss();
                        return;
                    }
                    HashMap<String, String> map=new HashMap<>();
                    map.put("mail",binding.loginMail.getText().toString());
                    map.put("password",binding.loginPassword.getText().toString());
                    Network.post(map, "user/login", call -> {
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                runOnUiThread(() -> {
                                    e.printStackTrace();
                                    loading_dialog.dismiss();
                                });
                            }
                            @Override
                            public void onResponse(@NonNull Call call, @NonNull Response response) {
                                runOnUiThread(() -> {
                                    loading_dialog.dismiss();
                                    try {
                                        String str= Objects.requireNonNull(response.body()).string();
                                        if (Tools.isJson(str)){
                                            JsonObject jo = JsonParser.parseString(str).getAsJsonObject();
                                            if (jo.get("message").getAsString().equals("Login success")){
                                                JsonObject userinfo = jo.get("data").getAsJsonObject();
                                                SharedPreferences.Editor edit = App.sp.edit();
                                                edit.putString("token",userinfo.get("token").getAsString());
                                                edit.apply();
                                                App.userBean =new Gson().fromJson(userinfo.get("user").getAsJsonObject(), UserBean.class);
                                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                                finish();
                                            }else {
                                                if (jo.get("message").getAsString().equals("Enter a valid email")){
                                                    launcher.launch(new Intent(LoginActivity.this, RegisterActivity.class));
                                                }else{
                                                    Tools.toast(jo.get("message").getAsString());
                                                }
                                            }
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                });
                            }
                        });
                        calls.add(call);
                    });
                }
            }
        });
        binding.loginRegister.setOnClickListener(v ->{
            if (checkDoubleClick()){
                launcher.launch(new Intent(LoginActivity.this, RegisterActivity.class));
            }
        } );
        binding.forgetPassword.setOnClickListener(v ->{
            if (checkDoubleClick()){
                launcher.launch(new Intent(LoginActivity.this, ForgetPasswordVerifyActivity.class));
            }
        } );
        binding.loginAgreement.setText(Tools.checkReadAutoLink(this));
        binding.loginAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        launcher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode()==2){//注册成功
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
            }
            if (result.getResultCode()==4){//注册回到要到找回密码
                startActivity(new Intent(LoginActivity.this,ForgetPasswordVerifyActivity.class));
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (Call call:calls) call.cancel();
        binding=null;
    }
    private long mClickTime;
    private boolean checkDoubleClick() {
        boolean result= mClickTime < SystemClock.uptimeMillis() - 500;
        mClickTime = SystemClock.uptimeMillis();
        return result;
    }
}